package com.itheima.demo;

import com.itheima.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Demo1 {
    private SqlSession session =null;
    private InputStream is =null;

    @Before
    public void before()throws Exception{
        //1.读取核心配置文件
    /*   is = Resources.getResourceAsStream("sql.xml");
        //2.构建SqlSessionFactory对象
       SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        //3.获取SqlSession对象
        session = factory.openSession();*/
        is = Resources.getResourceAsStream("sql.xml");
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(is);
        session = build.openSession();
    }

    @After
    public void after() throws Exception{
        //5.事务提交
        session.commit();
        //6.释放资源
        session.close();
        is.close();
    }

    @Test
    public void testFindSex(){
        List <Map> map = session.selectList("one.findBySex");
        Map sexMap = new HashMap();
        for (Map m : map) {
            String sex = (String) m.get("sex");
            Long total = (Long) m.get("count(*)");

            sexMap.put(sex, total);
        }
        System.out.println(sexMap);
    }

    @Test
    public void testFindCount ()throws Exception{
        Integer i = session.selectOne("one.findCount");
        System.out.println(i);
    }

    @Test
    public void testFindById() throws Exception{
        //4.调用statement对象并执行
        User user = session.selectOne("one.findById", 1);
        System.out.println(user);
    }

    //查询所有
    @Test
    public void testFindAll() throws Exception{
        //4.调用statement对象并执行
        List<User> list = session.selectList("one.findAll");
        System.out.println(list);

    }

    @Test
    public void testUpdateById() throws Exception{
        User user = session.selectOne("one.findById", 1);
        user.setUsername("刘学");
        session.update("one.updateById",user);
    }

    @Test
    public void testfindByEmailAndPwd(){
        Map map = new HashMap();
        map.put("em", "123@qq.com");
        map.put("pd", "123456");
        User user = session.selectOne("one.findByEmailAndPwd", map);
        System.out.println(user);
    }

    @Test
    public void testFind(){
        List <User> list = session.selectList("one.findLikeName", "%刘%");
        System.out.println(list);
    }


}
